<!DOCTYPE html>
<html style="width:100%">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>订单支付</title>
    <link rel="stylesheet" href="../../icon/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../../icon/iconfont.css">
    <link rel="stylesheet" type="text/css" href="../../css/api.css" />
    <link rel="stylesheet" href="../../css/aui.css">
    <style>
        body{
          background: #f3f3f3 !important;
        }
        header{
          padding: 1.6rem 0.8rem 0.5rem 0.8rem;
          position: fixed;
          width: 100%;
          background-color: #fff;
          z-index: 98;
          border-bottom: 1px solid #ccc
        }
        header span:nth-of-type(1){
          font-size: 1rem
        }
        header span:nth-of-type(2){
          font-size: 1rem
        }
        #content{
          background: #F3F3F3;
          padding-top: 4rem;
        }
        .info_content{
          margin: .5rem 0;
          border:5px solid #F3F3F3;
          border-left: 0;
          border-right: 0;
        }

        .pay_mode{
          margin: 0 auto;
          border-radius: 10px;
          width: 95%;
        }
        .items{
          background: #FFF;
        }
        .items p{
          display: flex;
          padding: 10px .5rem;
          justify-content: space-between;
          align-items: center;
        }
        .gary{
          font-size: 12px;
          color:#444;
        }
        .big{
          font-size: .8rem;
          color:#000;
        }
        i.kong,i.payicon{
          color:#D59B4F !important;
          font-size: 1.2rem !important;
        }
        .icon-bg{
          background-image: url("../../image/img/icon.png");
          width: 40px;
          height: 40px;
          background-repeat: no-repeat;
        }
        .bg-quan{
          background-position: -66px -10px;
        }
        .bg-yue{
          background-position: -21px -158px;
        }
        .bg-jifen{
          background-position: -15px -7px;
        }
        .bg-wechat{
          background-position: -15px -66px;
        }
        .bg-alipay{
          background-position: -17px -111px;
        }
        .text-color{
          color: #ecbb6f;
          font-weight: bold;
        }
        #payPost{
          background: #D59B4F;
          color: #FFF;
          text-align: center;
          width: 100%;
          padding: 1rem;
          line-height: .25rem;
          margin: 3rem 0 0 0;
        }
    </style>
</head>

<body style="background-color:rgb(255, 255, 255);color:rgb(57, 57, 57);margin:0;padding:0;width:100%;">
  <header>
    <span class="iconfont icon-fanhui" onClick="api.closeWin()"></span>
    <span>订单支付</span>
  </header>
  <div id="content"></div>
</body>
</html>
<script type="text/javascript" src="../../script/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../../lib/artTemplate/template.js"></script>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/dns.js"></script>
<script type="text/javascript" src="../../script/aui-toast.js"></script>
<script type="text/html" id="infoTpl">
    <div class="info_title items">
      <p class="big">{{datas.merchant_name}}</p>
      <p class="gary">{{datas.hotel_name}}</p>
      <p style="font-size: 12px;">{{datas.start_time}}<span class="gary">入住</span>{{datas.end_time}}<span class="gary">离店</span>{{datas.days}}<span class="gary">晚</span>{{datas.num}}<span class="gary">间</span></p>
    </div>
    <div class="info_content items">
      <p class="big">订单详情</p>
      <p><span class="gary">费用明细</span><span class="big">房费</span><span class="big">&yen;{{datas.price}}</span></p>
      <p><span class="gary">入住人</span><span class="big">{{datas.name}}</span></p>
      <p><span class="gary">联系电话</span><span>{{datas.mobile}}</span></p>
      <p><span class="big">应付金额：<label style="color:#D59B4F;font-size:1rem;" for="total">&yen;{{datas.price}}</label></span></p>
    </div>
    <div class="pay_mode items">
      <p><span class="icon-bg bg-quan"></span><span class="text-color" onclick="openCoupon({{datas.price}})">查看可用优惠券</span><span class="coupon_num"></span><span></span></p>
      <p><span class="icon-bg bg-yue"></span><span>可用余额</span>{{datas.balance}}<span><i style="cursor: pointer;" data-type="0" class="fa fa-square-o kong kyue"></i></span></p>
      <p><span class="icon-bg bg-jifen"></span><span>可用积分</span>{{datas.integral}}<span><i style="cursor: pointer;" data-type="0" class="fa fa-square-o kong kjifen"></i></span> </p>
      <p>
        <span class="icon-bg bg-wechat"></span>微信支付<span><i style="cursor: pointer;" data-type="wxpay" data-wxpay="0" class="fa fa-circle-o payicon wxpay"></i></span>
        <span class="icon-bg bg-alipay"></span>支付宝支付<span><i style="cursor: pointer;" data-type="alipay" data-alipsy="0" class="fa fa-circle-o payicon alipay"></i></span>
      </p>
    </div>
    <button id="payPost">提交订单</button>
</script>
<script>
    var toast = new auiToast({});
    var mid,total,is_integral,is_balance;
    var paytype = 0; //支付方式
    apiready = function() {
      localStorage.setItem("cid", '0,0')
      var pay_id = api.pageParam.payid;
      var pay_title = api.pageParam.paytitle;
      $('.toptitle').html(pay_title);
      getinfo(pay_id);
    };

    $(document).on('click','.kjifen',function(){
      if($(this).hasClass('fa-square-o')){
        $(this).removeClass('fa-square-o');
        $(this).addClass('fa-check-square');
        $(this).attr('data-type','1');
        is_integral = 1;
      }else{
        $(this).addClass('fa-square-o');
        $(this).removeClass('fa-check-square');
        $(this).attr('data-type','0');
        is_integral = 0;
      }
    });

    $(document).on('click','.kyue',function(){
      if($(this).hasClass('fa-square-o')){
        $(this).removeClass('fa-square-o');
        $(this).addClass('fa-check-square');
        $(this).attr('data-type','1');
        is_balance = 1;
      }else{
        $(this).addClass('fa-square-o');
        $(this).removeClass('fa-check-square');
        $(this).attr('data-type','0');
        is_balance = 0;
      }
    });

    $(document).on('click','.payicon',function(){
      var status = $(this).data('type');
      if (status == 'wxpay') {
          paytype = 1;
      }else{
        paytype = 2;
      }
      $('.payicon').removeClass('fa-dot-circle-o')
      $(this).addClass('fa-dot-circle-o');
    });

    //基本信息查询
    function getinfo(id) {
      console.log(localStorage.getItem('token'));
      console.log(id);
      toast.loading({
          title:"加载中...",
        },function(ret){
      });
      $.ajax({
          url: dns + 'hotelorder/detail',
          type: 'POST',
          dataType: 'json',
          data: {'id':id},
          beforeSend: function(request) {
              request.setRequestHeader("token", localStorage.getItem('token'));
          },
          success: function(res) {
             console.log(JSON.stringify(res));
            if(res.status == 1){
              setTimeout(function(){
                toast.hide();
                var html = template("infoTpl", {'datas':res.data});
                $('#content').html(html);
                mid = res.data.mid;
                total = res.data.price;
              },1000);
              api.addEventListener({
                  name: 'myEvent_coupon'
              }, function(ret, err){
                  if( ret ){
                    console.log(JSON.stringify(ret));
                    $(".coupon_num").html('已选用'+ret.value.face_value+'元优惠券');
                  }
              });

            }

          },
          error: function(err) {
              api.toast({
                  msg: JSON.parse(err.responseText).msg,
                  duration: 2000,
                  location: 'bottom' //'bottom'
              });
              return;
          }
      });
    }

    function openCoupon(total) {//选择优惠券
      api.openWin({
          name: 'useCoupon',
          url: './useCoupon.html',
          bgColor: '#f1f1f1',
          pageParam: {//页面代参数
            mid,
            total
          },
          rect: {
              x: 0,
              y: 25,
              w: api.winWidth,
              h: api.winHeight
          }
      });

    }
    //确认支付
    $(document).on('click','#payPost',function(){
        var yuestatus = $('.kyue').attr('data-type');
          if(yuestatus == 0){
            is_balance = 0
          }else{
            is_balance = 1
          }

        var jifenstatus = $('.kjifen').attr('data-type');
          if(jifenstatus == 0){
            is_integral = 0
          }else{
            is_integral = 1
          }
        var dataList = {
            'total': total,
            'mid': mid,
            'cid': localStorage.getItem("cid"),
            'is_integral': is_integral,
            'is_balance': is_balance,
            'type':paytype
        };
        Paypost(dataList,paytype);
    });

    //确认支付
    function Paypost(data,paytype) {
        if(paytype == 1) {  //微信支付
          $('#payPost').attr('disabled','disabled');
          serverWXPay(data);
        };
        if(paytype == 2) { // 支付宝支付
          $('#payPost').attr('disabled','disabled');
          serverAlipay(data);
        };
        if(paytype == 0) {
         // 余额支付或者积分支付
         console.log(JSON.stringify(data))
        $('#payPost').attr('disabled','disabled');
          $.ajax({
              url: g_serverApi + 'v2/pay/confirmorder',
              type: 'POST',
              dataType: 'json',
              data: data,
              beforeSend: function(request) {
                  request.setRequestHeader("token", localStorage.getItem('token'));
              },
              success: function(msg) {
                  if (msg.code == '20000') {
                    if(msg.msg != '支付成功'){
                      api.toast({
                          msg: msg.msg,
                          duration: 2000,
                          location: 'bottom' //'bottom'
                      });
                      $('#payPost').removeAttr('disabled');
                      return;
                    }
                    //提交订单号
                    $.ajax({
                        url: dns + 'hotelorder/bindorder',
                        type: 'POST',
                        dataType: 'json',
                        data: {'id':api.pageParam.payid,'ordersn':msg.data.order_no},
                        beforeSend: function(request) {
                            request.setRequestHeader("token", localStorage.getItem('token'));
                        },
                        success: function(msg) {
                          //console.log(JSON.stringify(msg.list));
                          if(msg.status == 1){
                            api.toast({
                                msg:'支付成功',
                                duration: 2000,
                                location: 'bottom' //'bottom'
                            });
                            setTimeout(function() {
                              $('.kong').removeClass('fa-check-square');
                              $('.payicon').removeClass('fa-dot-circle-o');
                              $('.kong').addClass('fa-square-o');
                              $('.payicon').addClass('fa-circle-o');
                              $('#payPost').removeAttr('disabled');
                              var pay_id = api.pageParam.payid;
                              getinfo(pay_id); //监听余额 积分 变化
                                api.openWin({
                                    name: 'banner',
                                    url: '../frame4/order/index.html',
                                    allowEdit:true,
                                    pageParam: {'pay':'ispay'}, //页面代参数
                                });
                            }, 1500);
                          }else{
                            api.toast({
                                msg: msg.msg,
                                duration: 2000,
                                location: 'bottom' //'bottom'
                            });
                          }
                        },
                        error: function(err) {
                            api.toast({
                                msg: JSON.parse(err.responseText).msg,
                                duration: 2000,
                                location: 'bottom' //'bottom'
                            });
                            $('#payPost').removeAttr('disabled');
                            return;
                        }
                    });
                  }
              },
              error: function(err) {
                  api.toast({
                      msg: JSON.parse(err.responseText).msg,
                      duration: 2000,
                      location: 'bottom' //'bottom'
                  });
                    $('#payPost').removeAttr('disabled');
                  return;
              }
          });
        }

    }

    //服务器支付宝预订单支付
    function serverAlipay(data) {
        $.ajax({
            url: g_serverApi + 'v2/pay/confirmorder',
            type: "POST",
            data:data,
            dataType: 'json',
            beforeSend: function(request) {
                request.setRequestHeader("token", localStorage.getItem('token'));
            },
            success: function(res) {　　
                 console.log(JSON.stringify(res));　
                // 调取apicloud 支付功能
                if(res.msg == '支付成功'){
                  toast.success({
                      title: "支付成功",
                      duration: 2000
                  });
                  //提交订单号
                  $.ajax({
                      url: dns + 'hotelorder/bindorder',
                      type: 'POST',
                      dataType: 'json',
                      data: {'id':api.pageParam.payid,'ordersn':res.data.order_no},
                      beforeSend: function(request) {
                          request.setRequestHeader("token", localStorage.getItem('token'));
                      },
                      success: function(msg) {
                        //console.log(JSON.stringify(msg.list));
                        if(msg.status == 1){
                          setTimeout(function() {
                            $("input[name='totalprice']").val('');
                            $('.kong').removeClass('fa-check-square');
                            $('.payicon').removeClass('fa-dot-circle-o');
                            $('.kong').addClass('fa-square-o');
                            $('.payicon').addClass('fa-circle-o');
                            $('#payPost').removeAttr('disabled');
                            var pay_id = api.pageParam.payid;
                            getinfo(pay_id); //监听余额 积分 变化
                              api.openWin({
                                  name: 'banner',
                                  url: '../frame4/order/index.html',
                                  allowEdit:true,
                                  pageParam: {'pay':'ispay'}, //页面代参数
                              });
                          }, 1500)
                        }else{
                          api.toast({
                              msg: msg.msg,
                              duration: 2000,
                              location: 'bottom' //'bottom'
                          });
                        }
                      },
                      error: function(err) {
                          api.toast({
                              msg: JSON.parse(err.responseText).msg,
                              duration: 2000,
                              location: 'bottom' //'bottom'
                          });
                          $('#payPost').removeAttr('disabled');
                          return;
                      }
                  });
                }else{
                  //提交订单号
                  $.ajax({
                      url: dns + 'hotelorder/bindorder',
                      type: 'POST',
                      dataType: 'json',
                      data: {'id':api.pageParam.payid,'ordersn':res.data.out_trade_no},
                      beforeSend: function(request) {
                          request.setRequestHeader("token", localStorage.getItem('token'));
                      },
                      success: function(msg) {
                        //console.log(JSON.stringify(msg.list));
                        if(msg.status == 1){
                            AliPay(res);
                        }else{
                          api.toast({
                              msg: msg.msg,
                              duration: 2000,
                              location: 'bottom' //'bottom'
                          });
                        }
                      },
                      error: function(err) {
                          api.toast({
                              msg: JSON.parse(err.responseText).msg,
                              duration: 2000,
                              location: 'bottom' //'bottom'
                          });
                          $('#payPost').removeAttr('disabled');
                          return;
                      }
                  });

                }

            },
            error: function(err) {
                toast.fail({
                    title: "请重新发起支付",
                    duration: 2000
                });
                  $('#payPost').removeAttr('disabled');
                return;
            }
        });
    };

    //apiCloud支付宝支付
    function AliPay(serverData) {
        var aliPay = api.require('aliPay');
        aliPay.config({
            partner: serverData.data.partner,
            seller: serverData.data.seller,
            rsaPriKey: serverData.data.rsaPriKey,
            rsaPubKey: serverData.data.rsaPubKey,
            notifyURL: serverData.data.notify_url
        }, function(ret, err) {
            if (ret.status) {
                aliPay.pay({
                    subject: serverData.data.subject,
                    body: serverData.data.body,
                    amount: serverData.data.total_fee,
                    tradeNO: serverData.data.out_trade_no,
                }, function(ret, err) {
                  if(ret.code=="9000"){
                    toast.success({
                        title: "支付成功!",
                        duration: 2000
                    });
                    setTimeout(function() {
                      $('.kong').removeClass('fa-check-square');
                      $('.payicon').removeClass('fa-dot-circle-o');
                      $('.kong').addClass('fa-square-o');
                      $('.payicon').addClass('fa-circle-o');
                      $('#payPost').removeAttr('disabled');
                        api.openWin({
                            name: 'banner',
                            url: '../frame4/order/index.html',
                            allowEdit:true,
                            pageParam: {'pay':'ispay'}, //页面代参数
                        });
                    }, 1500)
                  }else{
                    toast.fail({
                        title: "未支付成功!",
                        duration: 2000
                    });
                      $('#payPost').removeAttr('disabled');
                  }
                });
            } else {
               api.alert({
                 title: '支付结果',
                 msg: err.msg,
                 buttons: ['确定']
               });
          }
        });

    }

    //服务器微信预订单支付
    function serverWXPay(data) {
        $.ajax({
            url: g_serverApi + 'v2/pay/confirmorder',
            type: "POST",
            data:data,
            dataType: 'json',
            beforeSend: function(request) {
                request.setRequestHeader("token", localStorage.getItem('token'));
            },
            success: function(res) {　　
                 //console.log(JSON.stringify(res));　
                // 调取apicloud 支付功能
                if(res.msg == '支付成功'){
                  toast.success({
                      title: "支付成功",
                      duration: 2000
                  });
                  //提交订单号
                  $.ajax({
                      url: dns + 'hotelorder/bindorder',
                      type: 'POST',
                      dataType: 'json',
                      data: {'id':api.pageParam.payid,'ordersn':res.data.order_no},
                      beforeSend: function(request) {
                          request.setRequestHeader("token", localStorage.getItem('token'));
                      },
                      success: function(msg) {
                        //console.log(JSON.stringify(msg.list));
                        if(msg.status == 1){
                          setTimeout(function() {
                            $('.kong').removeClass('fa-check-square');
                            $('.payicon').removeClass('fa-dot-circle-o');
                            $('.kong').addClass('fa-square-o');
                            $('.payicon').addClass('fa-circle-o');
                            $('#payPost').removeAttr('disabled');
                            var pay_id = api.pageParam.payid;
                            getinfo(pay_id); //监听余额 积分 变化
                              api.openWin({
                                  name: 'banner',
                                  url: '../frame4/order/index.html',
                                  allowEdit:true,
                                  pageParam: {'pay':'ispay'}, //页面代参数
                              });
                          }, 1500)
                        }else{
                          api.toast({
                              msg: msg.msg,
                              duration: 2000,
                              location: 'bottom' //'bottom'
                          });
                        }
                      },
                      error: function(err) {
                          api.toast({
                              msg: JSON.parse(err.responseText).msg,
                              duration: 2000,
                              location: 'bottom' //'bottom'
                          });
                          $('#payPost').removeAttr('disabled');
                          return;
                      }
                  });
                }else{
                  //提交订单号
                  $.ajax({
                      url: dns + 'hotelorder/bindorder',
                      type: 'POST',
                      dataType: 'json',
                      data: {'id':api.pageParam.payid,'ordersn':res.data.tradeNo},
                      beforeSend: function(request) {
                          request.setRequestHeader("token", localStorage.getItem('token'));
                      },
                      success: function(msg) {
                        //console.log(JSON.stringify(msg.list));
                        if(msg.status == 1){
                            Wxpay(res);
                        }else{
                          api.toast({
                              msg: msg.msg,
                              duration: 2000,
                              location: 'bottom' //'bottom'
                          });
                        }
                      },
                      error: function(err) {
                          api.toast({
                              msg: JSON.parse(err.responseText).msg,
                              duration: 2000,
                              location: 'bottom' //'bottom'
                          });
                          $('#payPost').removeAttr('disabled');
                          return;
                      }
                  })

                }
            },
            error: function(err) {
                toast.fail({
                    title: "请重新发起支付",
                    duration: 2000
                });
                  $('#payPost').removeAttr('disabled');
                return;
            }
        });
    }

    //apiCloud微信支付
    function Wxpay(serverData) {
        var wxPay = api.require('wxPay');
        wxPay.config({
            apiKey: serverData.data.apiKey,
            mchId: serverData.data.mchId,
            partnerKey: serverData.data.partnerKey,
            notifyUrl: serverData.data.notifyUrl
        }, function(ret, err) {
            if (ret.status) {
                wxPay.pay({
                    description: serverData.data.description,
                    totalFee: serverData.data.totalFee,
                    tradeNo: serverData.data.tradeNo
                }, function(ret, err) {
                    // 用户正常行为点击了 返回商户 按钮
                    if (ret.status) {
                        toast.success({
                            title: "支付成功",
                            duration: 1500
                        });
                        setTimeout(function() {
                          $('.kong').removeClass('fa-check-square');
                          $('.payicon').removeClass('fa-dot-circle-o');
                          $('.kong').addClass('fa-square-o');
                          $('.payicon').addClass('fa-circle-o');
                          $('#payPost').removeAttr('disabled');
                            api.openWin({
                                name: 'banner',
                                url: '../frame4/order/index.html',
                                allowEdit:true,
                                pageParam: {'pay':'ispay'}, //页面代参数
                            });
                        }, 1500)
                    } else {
                        toast.fail({
                            title: "支付失败",
                            duration: 2000
                        });
                          $('#payPost').removeAttr('disabled');
                        return;
                    }
                });
            } else {
                toast.success({
                    title: "支付失败",
                    duration: 1500
                });
                setTimeout(function() {
                    $('#payPost').removeAttr('disabled');
                    api.closeWin();
                }, 2000)

                return;
            }
            // 心跳查询该笔订单
            var orderStatus = setInterval(function() {
                getOrderStatus(serverData.data.tradeNo)
            }, 1000);
        });
    }

    //查询订单支付状态
    function getOrderStatus(order_no) {
        $.ajax({
            url: g_serverApi + 'va2/pay/status?order=' + order_no,
            type: "GET",
            dataType: 'json',
            beforeSend: function(request) {
                request.setRequestHeader("token", localStorage.getItem('token'));
            },
            success: function(res) {　　
                // clearInterval(orderStatus)
                toast.success({
                    title: "支付成功",
                    duration: 1500
                });
                setTimeout(function() {
                    api.closeWin()
                }, 2000)
            },
            error: function(err) {
              return;
                toast.loading({
                    title: "请稍候",
                    duration: 2000
                }, function(ret) {

                });
                return;
            }
        });
    }

</script>
